package com.william.thirdpart.common;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.Dictionary;
import java.util.Map;

/**
 * ApiBase class
 *
 * @author william
 * @date 2021/1/12
 */
@Service
@Slf4j
public abstract class ApiBase {
    @Value("${wormface.host}")
    public String host;
    @Autowired
    public RestTemplate restTemplate;
    public void get(){
        //restTemplate.getForEntity()
    }

    /**
     * form方式提交
     * @param map
     */
    public void postForm(Dictionary<String,String> map){
    }
    /**
     * post请求，通过body传递数据
     * @return
     */
    public String postBody(){
        String url=getUrl();
        log.info("request:{}:{}",url, LocalDateTime.now().toString());
        HttpHeaders httpHeaders=new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);

        HttpEntity<String> httpEntity=new HttpEntity<>(buildRequestBody(),httpHeaders);
        ResponseEntity<String> response=restTemplate.exchange(url, HttpMethod.POST,httpEntity,String.class);
        return response.getBody();
    }

    /**
     * post请求时，返回bady内容
     * @return
     */
    public  String buildRequestBody(){
        return buildRequestBodyByMap(getParasMap());
    }
    public Map<String,Object> getParasMap(){
        return Maps.newHashMap();
    }
    public  String buildRequestBodyByMap(Map<String,Object> bodyMap){
        JSONObject jsonObject = new JSONObject();
        for(Map.Entry<String,Object> kvp:bodyMap.entrySet()){
            jsonObject.put(kvp.getKey(),kvp.getValue());
        }
        return  jsonObject.toString();
    }
    /**
     * 获取完整的请求url
     * @return
     */
    public String getUrl(){
        return host+getLocation();
    }

    /**
     * api的请求地址
     * @return
     */
    abstract String getLocation();
}

